using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Threading;

public class RealRandom
{
    private RNGCryptoServiceProvider m_RNG = new RNGCryptoServiceProvider();

    public int Random(int min, int max)
    {
        byte[] buffer = new byte[4];
        m_RNG.GetBytes(buffer);
            
        int value = BitConverter.ToInt32(buffer, 0);
        if (value < 0) value = -value;
        return min + (value % (max - min));
    }

    #region Test
    
    public static void ThreadTest()
    {
        _count0 = 0;
        _count1 = 0;
        new Thread(ThreadFunction).Start();
        new Thread(ThreadFunction).Start();
        new Thread(ThreadFunction).Start();
        new Thread(ThreadFunction).Start();
        new Thread(ThreadFunction).Start();
    }

    static object lockObject = new object();
    static int _count0 = 0;
    static int _count1 = 0;
    static void ThreadResult(int count0, int count1)
    {
        lock (lockObject)
        {
            _count0 += count0;
            _count1 += count1;
            GameDebug.Log($"{Thread.CurrentThread.ManagedThreadId}, count0: {_count0}, count1: {_count1}");
        }
    }

    static RealRandom _random = new RealRandom();
    static void ThreadFunction()
    {
        int min = 0;
        int max = 2;
        
        List<int>[] lists = new List<int>[max - min];
        for (int i = min; i < max; ++i)
        {
            lists[i] = new List<int>();
        }

        for (int i = 0; i < 100000; ++i)
        {
            int value = _random.Random(min, max);
            List<int> list = lists[value - min];
            list.Add(value);
        }

        int count0 = lists[0].Count;
        int count1 = lists[1].Count;

        ThreadResult(count0, count1);
    }
    
    #endregion
}